﻿#include "redis_async_pub.h"
#include <hiredis/async.h>
#include <hiredis/hiredis.h>
#include <event.h>
#include <hiredis/adapters/libevent.h>
#include <spdlog/spdlog.h>
#include <iostream>
using namespace std;
namespace pub {

    static struct event_base* base = nullptr;
    static redisAsyncContext* context = nullptr;
    // 静态成员变量的定义
    bool redis_async_pub::is_initialized = false;

    redis_async_pub::redis_async_pub(const int port, const char* ip) : redis_port(port), redis_ip(ip) {}

    redis_async_pub::~redis_async_pub() {
        if (is_initialized) {
            redisAsyncDisconnect(context);
            event_base_free(base);
        }
    }

    void redis_async_pub::init() {
        if (is_initialized) {
            spdlog::info("【Redis_Pub】：Error: Redis async pub is already initialized.");
            return;
        }

        base = event_base_new();
        context = redisAsyncConnect(redis_ip, redis_port);
        if (context->err) {
            spdlog::info("【Redis_Pub】：Error: {}", context->errstr);
            redisAsyncFree(context);
            event_base_free(base);
            return;
        }

        redisLibeventAttach(context, base);
        redisAsyncSetConnectCallback(context, [](const redisAsyncContext* ctx, int status) {
            if (status != REDIS_OK) {
                spdlog::info("【Redis_Pub】：Error: {}", ctx->errstr);
            }
            else {
                spdlog::info("【Redis_Pub】：Connected to Redis server.");
            }
            });
        redisAsyncSetDisconnectCallback(context, [](const redisAsyncContext* ctx, int status) {
            if (status != REDIS_OK) {
                spdlog::info("【Redis_Pub】：Error: ", ctx->errstr);
            }
            else {
                spdlog::info("【Redis_Pub】：Disconnected from Redis server.");
            }
            });

        is_initialized = true;
    }

    void redis_async_pub::publish(const string& channel, const string& message) {
        if (!is_initialized) {
            spdlog::info("【Redis_Pub】：Error: Redis async pub is not initialized.");
            return;
        }

        redisAsyncCommand(context, NULL, NULL, "PUBLISH %s %s", channel.c_str(), message.c_str());
        spdlog::info("【Redis_Pub】：send channel: {}", channel);
        spdlog::info("【Redis_Pub】：send message: {}", message);
    }

} // namespace pub